<?php
namespace app\admin\controller;

use app\common\model\CommonModel;
use app\common\model\EsModel;
use think\facade\Log;

class Elastic extends Common
{
    /**
     * 同步数据库表的数据到 elasticsearch
     * @author 贺强
     * @time   2022/3/22 11:07
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $database = env('database.database', '');
            $prefix = env('database.prefix', '');
            $tables = CommonModel::query("SELECT t.TABLE_NAME,t.TABLE_COMMENT FROM information_schema.`TABLES` t WHERE t.TABLE_SCHEMA='$database' AND t.TABLE_NAME NOT LIKE '{$prefix}user_log_%'");
            return view('', compact('tables'));
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $param = $this->request->post();
        foreach ($param as $k => $v) {
            if (!in_array($k, ['table', 'field', 'field_value', 'rel', 'size'])) {
                return ajax('非法参数', 301);
            }
            if (strpos($v, ' ') !== false || strpos($v, '`') !== false || strpos($v, '&') !== false) {
                return ajax('非法参数', 302);
            }
        }
        $table = $param['table'] ?? '';
        if (empty($table)) {
            return ajax('表名不能为空', 101);
        }
        $field = $param['field'] ?? '';
        $field_value = $param['field_value'] ?? '';
        $rel = $param['rel'] ?? '=';
        if ($rel === 'like' && !empty($field_value)) {
            $field_value = "%$field_value%";
        }
        $sql_c = "SELECT COUNT(*) c FROM `$table`";
        $sql = "SELECT * FROM `$table`";
        if (!empty($field) && !empty($field_value)) {
            $sql_c .= " WHERE `$field` $rel '$field_value'";
            $sql .= " WHERE `$field` $rel '$field_value'";
        }
        $res = CommonModel::query($sql_c);
        $count = $res[0]['c'];
        if ($count <= 0) {
            return ajax('暂无数据', 103);// 如果没数据直接返回
        }
        $index = 'es_index_' . $table;
        $data = compact('table', 'sql');
        if (empty($field) && empty($field_value) && EsModel::isExist($index)) {
            EsModel::delIndex($index);
        }
        $size = $this->request->post('size', 1000);
        $pages = intval(ceil($count / $size));
        for ($page = 0; $page < $pages; $page++) {
            $offset = $page * $size;
            $data['offset'] = $offset;
            $data['length'] = $size;
            queue('app\\common\\job\\EsJob@sync_data', $data);
        }
        return ajax('同步成功');
    }

    /**
     * 删除 es 索引
     * @author 贺强
     * @time   2023/5/17 11:06
     * @return string|\think\response\Json
     */
    public function del()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        try {
            $param = $this->request->post();
            foreach ($param as $k => $v) {
                if (!in_array($k, ['table', 'field', 'field_value', 'rel'])) {
                    return ajax('非法参数', 301);
                }
                if (strpos($v, ' ') !== false || strpos($v, '`') !== false || strpos($v, '&') !== false) {
                    return ajax('非法参数', 302);
                }
            }
            if (empty($param['table'])) {
                return ajax('表名不能为空', 101);
            }
            $field = $param['field'] ?? '';
            $field_value = $param['field_value'] ?? '';
            $index = 'es_index_' . $param['table'];
            if (!EsModel::isExist($index) && (empty($field) || empty($field_value))) {
                return ajax('索引不存在', 302);
            }
            $flag = false;
            if (!empty($field)) {
                $rel = $param['rel'] ?? '=';
                if ($rel === 'like') {
                    $field_value = "%$field_value%";
                }
                $where = [[$field, $rel, $field_value]];
                CommonModel::$tablename = $param['table'];
                $list = CommonModel::getList($where, ['id']);
                foreach ($list as $item) {
                    $flag = CommonModel::delById($item['id']);
                    if (!$flag) {
                        Log::error($index . '->' . $item['id']);
                    }
                }
            } else {
                $flag = EsModel::delIndex($index);
            }
            if ($flag) {
                return ajax('删除成功');
            }
            return ajax('删除失败', 400);
        } catch (\Exception $e) {
            Log::error($e);
            return ajax('服务器错误，请检查日志');
        }
    }
}
